<template>
<div class="bms-dict">
  <unfold>
    <!-- 左侧组名称列表 -->
    <template v-slot:tree-list>
      <div class="left box">

        <!-- header -->
        <div class="box-header bg-primary text-white text-weight-regular">
          <q-icon name="iconfont icontubiao-85" color="white" class="q-mr-sm" />
          <span class="head-title vertical-middle user-select-none">组名称</span>
        </div>

        <!-- 列表 -->
        <q-scroll-area class="box-content bg-white" :thumb-style="CommonConfig.thumbStyle">
          <q-list style="min-width: 100px;">
            <div v-for="dictionaryGroup in dictionaryGroups" :key="dictionaryGroup.code">
              <q-item
                class="role-item"
                :active="selectedRoleId === dictionaryGroup.code"
                active-class="activated"
                @click="onRoleClick(dictionaryGroup)"
                clickable
                v-ripple
              >
                <q-item-section>{{ dictionaryGroup.label }}</q-item-section>
              </q-item>
              <q-separator />
            </div>
          </q-list>
        </q-scroll-area>
      </div>
    </template>

    <!-- 右侧 card -->
    <template v-slot:content>
      <div class="right box">
        <div class="relative-position full-height box-content page-content">
          <!-- header -->
          <!--<div class="box-header bg-primary text-white text-weight-regular">-->
          <!--<q-icon name="iconfont icontubiao-86" color="white" class="q-mr-sm" />-->
          <!--<span class="head-title vertical-middle user-select-none">数据信息</span>-->
          <!--</div>-->
          <div class="form-inline" style="width: 100%">
            <q-btn class="margin-r-10" outline color="primary" label="新增" @click="openAddDialog" />
          </div>
          <q-table
            :pagination = "pagination"
            class="myTable scroll stick-last-col"
            :columns="columns"
            :data="tableData"
            :loading="isTableLoading"
            row-key="id"
            flat
            hide-bottom
            no-data-label="暂无数据"
          >
            <template v-slot:body="props">
              <q-tr :props="props">
                <q-td key="gname" :props="props">{{ selectedRoleName }}</q-td>
                <q-td key="label" :props="props">{{ props.row.label }}</q-td>
                <q-td key="value" :props="props">{{ props.row.value }}</q-td>
                <q-td key="remark" :props="props">{{ props.row.remark !== '' ?  props.row.remark : '--' }}</q-td>
                <q-td key="customerFlag" :props="props">{{ props.row.customerFlag ? '是(可删除)' : '否(不可删除)' }}</q-td>
                <q-td class="dict-status">
                  <div
                    class="indicator"
                    :class="{
                    negative: props.row.enableFlag === false,
                    positive: props.row.enableFlag === true
                  }"
                  >
                  </div>
                  <span
                    class="text"
                    :class="{
                    negative: props.row.enableFlag === false,
                    positive: props.row.enableFlag === true
                  }"
                  >
                  {{ props.row.enableFlagName }}
                </span>
                </q-td>
                <q-td class="operations" style="text-align: center; width: 250px">
                  <div class="btn-group">
                    <q-btn
                      flat round dense
                      :disabled="disableMoveUp(props.row)"
                      icon="iconfont icontubiao-88"
                      color="primary"
                      @click="moveUp(props.row)"
                    >
                      <q-tooltip>上移</q-tooltip>
                    </q-btn>
                    <q-btn
                      :disabled="disableMoveDown(props.row)"
                      flat round dense
                      icon="iconfont icontubiao-87"
                      color="primary"
                      @click="moveDown(props.row)"
                    >
                      <q-tooltip>下移</q-tooltip>
                    </q-btn>
                    <q-btn
                      flat round dense
                      icon="iconfont icontubiao-12"
                      color="primary"
                      @click="openEditDialog(props.row)"
                    >
                      <q-tooltip>编辑</q-tooltip>
                    </q-btn>
                    <q-btn
                      :disabled="!props.row.customerFlag"
                      flat round dense
                      icon="iconfont icontubiao-16"
                      color="primary"
                      @click="onDeleteClick(props.row.id)"
                    >
                      <q-tooltip>删除</q-tooltip>
                    </q-btn>
                    <q-toggle
                      v-model="props.row.enableFlag"
                      :true-value="statusToggleTrueVal"
                      :false-value="statusToggleFalseVal"
                      checked-icon="iconfont icontubiao-49"
                      unchecked-icon="iconfont icontubiao-48"
                      :disable="isStatusToggleDisabled[props.row.id]"
                      color="positive"
                      @input="onStatusToggle(props.row, $event)"
                    >
                      <template v-slot>
                        <q-tooltip>{{ getStatusToggleTip(props.row.enableFlag) }}</q-tooltip>
                      </template>
                    </q-toggle>
                  </div>
                </q-td>
              </q-tr>
            </template>
          </q-table>
        </div>
      </div>
    </template>
  </unfold>

  <add-dialog
    ref="dict"
    :show="dialog.show"
    :state="dialog.title"
    :dictionaryGroup = "dialog.dictionaryGroup"
    :dictionaryGroupCode= "dialog.dictionaryGroupCode"
    @close="dialog.show = false"
    @submit="submit"
  />
</div>
</template>

<script>
import Unfold from 'src/components/unfold'
import AddDialog from './components/add-edit-data-dict'
import { getDictgroup, getDictlistByCode, addDict, editDict, delDict, enableDict, sortDict } from 'src/boot/bms/bms-dict'
import refreshMixin from '../../assets/js/refresh-mixin'

export default {
  name: 'bms-dict',
  mixins: [refreshMixin],
  data () {
    return {
      dialog: {
        title: '', // 新增_编辑对话框的标题
        show: false, // 新增_编辑对话框显示_隐藏标识
        dictionaryGroup: '',
        dictionaryGroupCode: ''
      },
      isTableLoading: false, // 数据信息列表loading
      tableData: [], // 数据信息列表数据源
      dictionaryGroups: [], // 字典组
      statusToggleTrueVal: true, // 状态 toggle 为 true 时的 status 值
      statusToggleFalseVal: false, // 状态 toggle 为 false 时的 status 值
      selectedRoleId: null, // 选择的字典组
      selectedRoleName: null, // 选择的字典组
      isStatusToggleDisabled: {}, // 避免用户操作过快
      // 使分页每页显示无限条
      pagination: {
        rowsPerPage: 0
      },
      // 表格列标
      columns: [
        { name: 'gname', field: 'gname', label: '字典组', align: 'left' },
        { name: 'label', field: 'label', label: '内容', align: 'left' },
        { name: 'value', field: 'value', label: '值', align: 'left' },
        { name: 'remark', field: 'remark', label: '备注', align: 'left' },
        { name: 'customerFlag', field: 'customerFlag', label: '是否自定义', align: 'left' },
        { name: 'enableFlagName', field: 'enableFlagName', label: '是否可用', align: 'left' },
        { name: 'operations', field: 'operations', label: '操作', align: 'center' }
      ]
    }
  },
  created () {
    this.listLictionaryGroups()
  },
  methods: {
    /**
     * 全局刷新数据
     * author: xueli
     */
    refreshInfo () {
      this.listLictionaryGroups()
    },
    // 初始化字典组数据
    listLictionaryGroups () {
      getDictgroup().then(res => {
        this.dictionaryGroups = res.data
        return res.data[0]
      }).then(item => {
        this.selectedRoleId = item.code
        this.selectedRoleName = item.label
        this.getList()
      })
    },

    // 点击字典组列表
    onRoleClick (item) {
      this.selectedRoleId = item.code
      this.selectedRoleName = item.label
      this.getList()
    },

    // 获取字典项列表
    getList () {
      this.isTableLoading = true
      getDictlistByCode(this.selectedRoleId).then(res => {
        console.log(res)
        if (res.data.length !== 0) {
          for (const i of res.data) {
            i['enableFlag'] === false ? i['enableFlagName'] = '禁用' : i['enableFlagName'] = '启用'
          }
        }
        this.tableData = res.data
      }).finally(() => {
        this.isTableLoading = false
      })
    },

    // 切换字典项禁用/启用状态
    onStatusToggle (val, status) {
      this.$set(this.isStatusToggleDisabled, val.id, true)
      let params = {
        enableFlag: status
      }
      enableDict(val.id, params).then(() => {
        this.getList()
      }).finally(() => {
        this.$set(this.isStatusToggleDisabled, val.id, false)
      })
    },

    // 根据字典项启禁用推算toogle组件tooptip提示文字
    getStatusToggleTip: function (val) {
      return val ? '封禁' : '启用'
    },

    // 向上移动字典项
    moveUp (row) {
      let index
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].id === row.id) {
          index = i
          break
        }
      }
      if (index - 1 >= 0) {
        const id = this.tableData[index].id
        const nextId = this.tableData[index - 1].id
        let params = {
          id1: id,
          id2: nextId
        }
        sortDict(params).then(() => {
          this.getList()
        })
      }
    },

    // 项下移动字典项
    moveDown (row) {
      let index
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].id === row.id) {
          index = i
          break
        }
      }

      if (index < this.tableData.length - 1) {
        const id = this.tableData[index].id
        const nextId = this.tableData[index + 1].id
        let params = {
          id1: id,
          id2: nextId
        }
        sortDict(params).then(() => {
          this.getList()
        })
      }
    },

    // 向上移动按钮的条件禁用
    disableMoveUp (row) {
      if (this.tableData.indexOf(row) === 0) {
        return true
      } else {
        return false
      }
    },

    disabledDel (row) {
      if (row.customerFlag === 0) {
        return true
      } else {
        return false
      }
    },

    // 向下移动按钮的条件禁用
    disableMoveDown (row) {
      if (this.tableData.indexOf(row) === this.tableData.length - 1) {
        return true
      } else {
        return false
      }
    },

    // 删除字典项
    onDeleteClick (id) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要删除此项吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      })
        .onOk(() => {
          delDict(id).then(res => {
            if (res.code === '1200') {
              this.$message.success('删除成功')
            }
            this.getList()
          })
        })
    },

    // 判断选中的字典组列表code与label为传递给新增_编辑对话框准备数据

    filterDict () {
      for (const i of this.dictionaryGroups) {
        if (i['code'] === this.selectedRoleId) {
          this.dialog.dictionaryGroup = i['label']
          this.dialog.dictionaryGroupCode = i['code']
        }
      }
    },

    // 打开新增字典项窗口
    openAddDialog () {
      this.$refs.dict.reset()
      this.dialog.show = true
      this.dialog.title = 'add'
      this.filterDict()
    },

    // 打开编辑字典项窗口
    openEditDialog (row) {
      this.dialog.show = true
      this.dialog.title = 'edit'
      this.filterDict()
      this.$refs.dict.assignment(row)
    },

    // 提交表单
    submit (state, val) {
      const query = {
        enableFlag: val.enable,
        remark: val.remark,
        label: val.label,
        value: val.value
      }
      console.log(val)
      if (state === 'add') {
        addDict(this.selectedRoleId, query).then(res => {
          this.dialog.show = false
          if (res.code === '1200') {
            this.getList()
            this.$message.success('添加成功')
          }
        })
      } else {
        editDict(val.id, query).then(res => {
          this.dialog.show = false
          if (res.code === '1200') {
            this.getList()
            this.$message.success('编辑成功')
          }
        })
      }
    }
  },
  components: {
    Unfold,
    AddDialog
  }
}
</script>

<style scoped lang="stylus">
  .condition {
    width: 100%
    /*height: 40px*/
    margin-bottom 20px
    margin-top 20px
    margin-left 30px
  }
  .dict-status {
    .indicator {
      display inline-block
      border-radius 50%
      height 10px
      width 10px
      margin-right 2px

      &.positive {
        background $positive
      }

      &.negative {
        background $negative
      }
    }

    .text {
      &.positive {
        color $positive
      }

      &.negative {
        color $negative
      }
    }

  }
  .bms-dict {
    .box {
      display flex
      flex-direction column
      width 100%
      min-width 250px
      border-radius 6px
      overflow hidden
      height 100%

      .box-header {
        flex 40px 0
        padding 0 20px
        line-height 40px
        font-size 18px
      }

      &.left {
        .box-content {
          flex 1
          padding-bottom 20px

          .role-item {
            padding-left 30px
            font-size 16px

            &.activated {
              background #cfd6fe
              color $primary
            }

            &:hover {
              background #e8ebff

              /deep/ .q-focus-helper {
                display none
              }
            }
          }

          .q-separator {
            margin-left 20px
            width calc(100% - 40px)
          }
        }
      }

      &.right {
        .box-content {
          display flex
          flex-direction column
          flex 1
          padding-top 0

          .table-header {
            display flex
            justify-content space-between
            align-items center
            padding 0 16px 0 40px
            height 48px
            background #F3F3F3
            margin-top 30px

            &__right {
              display flex

              .table-header__item {
                padding-right 10px

                header-items-sparsity-s() {
                  &.type {
                    min-width 60px
                  }

                  &.parentMenu {
                    min-width 140px
                  }

                  &.toggle {
                    min-width 70px
                  }
                }

                header-items-sparsity-m() {
                  &.type {
                    min-width 100px
                  }

                  &.parentMenu {
                    min-width 220px
                  }

                  &.toggle {
                    min-width 104px
                  }
                }

                header-items-sparsity-m()

                @media screen and (min-width 1024px) and (max-width 1200px) {
                  header-items-sparsity-s()
                }

                @media screen and (max-width 1000px) {
                  header-items-sparsity-s()
                }
              }
            }
          }

          .menu-item-box {
            width 100%
            display flex
            justify-content space-between
            align-items center

            .wrapper {
              padding-right 10px
            }

            .right-box {
              display flex
              align-items center

              .wrapper {
                boxes-sparsity-s() {
                  &.type, &.toggle {
                    min-width 60px
                  }

                  &.parent-name {
                    min-width 140px
                  }
                }

                boxes-sparsity-m() {
                  &.type, &.toggle {
                    min-width 100px
                  }

                  &.parent-name {
                    min-width 220px
                  }
                }

                boxes-sparsity-m()

                @media screen and (min-width 1024px) and (max-width 1200px) {
                  boxes-sparsity-s()
                }

                @media screen and (max-width 1000px) {
                  boxes-sparsity-s()
                }
              }
            }
          }
        }
      }
    }
  }
</style>

<style lang="stylus">
  .data-dict{
    .myTable .q-table__middle{
      max-height calc(100%)
    }
  }
</style>
